package com.jianjun.framework.web.interceptor;

import cn.hutool.http.Method;
import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.ext.cors.EnableCORS;
import com.jfinal.kit.StrKit;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author source
 * {@code @date} 2025/1/8 13:18
 */
@EnableCORS(allowHeaders = "*", allowMethods = "*", maxAge = "1800")
public class CORSGlobalInterceptor implements Interceptor {
    static ThreadLocal<HttpServletRequest> TL_REQ = new ThreadLocal<>();

    public static HttpServletRequest getRequest() {
        return TL_REQ.get();
    }

    @Override
    public void intercept(Invocation inv) {
        TL_REQ.set(inv.getController().getRequest());
        EnableCORS enableCORS = getAnnotation();

        if (enableCORS == null) {
            inv.invoke();
            return;
        }

        doConfigCORS(inv, enableCORS);

        String method = inv.getController().getRequest().getMethod();
        if (Method.OPTIONS.name().equals(method)) {
            inv.getController().renderText("");
        } else {
            inv.invoke();
        }
    }

    private EnableCORS getAnnotation() {
        return this.getClass().getAnnotation(EnableCORS.class);
    }

    private void doConfigCORS(Invocation inv, EnableCORS enableCORS) {
        HttpServletResponse response = inv.getController().getResponse();
        String allowOrigin = enableCORS.allowOrigin();
        String allowCredentials = enableCORS.allowCredentials();
        String allowHeaders = enableCORS.allowHeaders();
        String allowMethods = enableCORS.allowMethods();
        String exposeHeaders = enableCORS.exposeHeaders();
        String requestHeaders = enableCORS.requestHeaders();
        String requestMethod = enableCORS.requestMethod();
        String origin = enableCORS.origin();
        String maxAge = enableCORS.maxAge();

        response.setHeader("Access-Control-Allow-Origin", allowOrigin);
        response.setHeader("Access-Control-Allow-Methods", allowMethods);
        response.setHeader("Access-Control-Allow-Headers", allowHeaders);
        response.setHeader("Access-Control-Max-Age", maxAge);
        response.setHeader("Access-Control-Allow-Credentials", allowCredentials);

        if (StrKit.notBlank(exposeHeaders)) {
            response.setHeader("Access-Control-Expose-Headers", exposeHeaders);
        }

        if (StrKit.notBlank(requestHeaders)) {
            response.setHeader("Access-Control-Request-Headers", requestHeaders);
        }

        if (StrKit.notBlank(requestMethod)) {
            response.setHeader("Access-Control-Request-Method", requestMethod);
        }

        if (StrKit.notBlank(origin)) {
            response.setHeader("Origin", origin);
        }

    }
}
